#include "blockqueue.hpp"
#include "task.hpp"
#include <ctime>
const std::string ops = "+-*/%";
void* consumer_run(void* arg){
    Blockqueue<Task>* blq=(Blockqueue<Task>*)arg;
    while(true){    //循环获取任务，并执行
        Task t=blq->pop();
        int result=t();
        int em1,em2;
        char op;
        t.get(&em1,&em2,&op);
        cout << "consumer[" << pthread_self() << "] " << (unsigned long)time(nullptr) 
        << " 消费了一个任务: " << em1 << op << em2 << "=" << result << endl;
    }
    return nullptr;
}
void* productor_run(void* arg){
    Blockqueue<Task>*blq=(Blockqueue<Task>*)arg;
    while (true)
    {
        int em1=rand()%100,em2=rand()%30;
        char op=ops[rand()%4];
        Task t(em1,em2,op);
        blq->push(t);
        cout << "producter[" << pthread_self() << "] " << (unsigned long)time(nullptr) 
        << " 生产了一个任务: " << em1 << op << em2 << "=?" << endl;
        sleep(1);
    }
    return nullptr;
}
int main(){
    srand((unsigned long)time(nullptr) ^ getpid());
    Blockqueue<Task> blq;   //创建一个阻塞队列
    pthread_t c1,c2,c3,c4,p1,p2,p3,p4,p5;
    pthread_create(&c1,nullptr,consumer_run,&blq);
    pthread_create(&c2,nullptr,consumer_run,&blq);
    pthread_create(&c3,nullptr,consumer_run,&blq);
    pthread_create(&c4,nullptr,consumer_run,&blq);
    pthread_create(&p1,nullptr,productor_run,&blq);
    pthread_create(&p2,nullptr,productor_run,&blq);
    pthread_create(&p3,nullptr,productor_run,&blq);
    pthread_create(&p4,nullptr,productor_run,&blq);
    pthread_create(&p5,nullptr,productor_run,&blq);
    //回收线程
    pthread_join(c1,nullptr);
    pthread_join(c2,nullptr);
    pthread_join(c3,nullptr);
    pthread_join(c4,nullptr);
    pthread_join(p1,nullptr);
    pthread_join(p2,nullptr);
    pthread_join(p3,nullptr);
    pthread_join(p4,nullptr);
    pthread_join(p5,nullptr);
    return 0;
}

